package com.jzy.bxb.app.scripts.http.order;

import java.util.Date;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.jzy.bxb.app.manager.OrderManager;
import com.jzy.bxb.app.manager.RedisManager;
import com.jzy.bxb.app.server.AuthHttpHandler;
import com.jzy.bxb.core.handler.HandlerEntity;
import com.jzy.bxb.model.constant.OrderState;
import com.jzy.bxb.model.constant.RedisKey;
import com.jzy.bxb.model.mongo.dao.OrderDao;
import com.jzy.bxb.model.mongo.dao.UserDao;
import com.jzy.bxb.model.mongo.entity.Order;
import com.jzy.bxb.model.mongo.entity.User;
import com.jzy.bxb.model.util.UMPushUtil;

import redis.clients.jedis.Jedis;

/**
 * 创建订单
 * <p>
 * http://127.0.0.1:8680/order/create?&sid=4c97b38b-7922-41c2-b367-93723f82ed76
 * http://112.74.36.233:8680/order/create?&sid=daa0cf5b-e72d-422c-b278-450b28a702c6
 * <br>
 * 
 * </p>
 * 
 * @author JiangZhiYong
 * @date 2017-07-12 QQ:359135103
 */
@HandlerEntity(path = "/order/create")
public class CreateOrderHandler extends AuthHttpHandler {
	private static final Logger LOGGER = LoggerFactory.getLogger(CreateOrderHandler.class);

	@Override
	public void run() {

		if (user.getAddress() == null) {
			sendError("请先设置地址");
			return;
		}
		String addressStr = OrderManager.getInstance().getRedisAddressStr(user.getAddress());

		Jedis client = RedisManager.getInstance().getClient();
		String userIdStr = client.hget(RedisKey.AreaAssistantMap.getKey(), addressStr);
		if (userIdStr == null) {
			LOGGER.info("{} 没有可用服务", addressStr);
			sendError("下单失败  小帮今天在偷懒");
			return;
		}
		Order order = new Order();
		order.setEmployerId(user.getId());
		order.setState(OrderState.CREATE.getState());
		order.setAddress(user.getAddress());
		order.setCreateTime(new Date());
		Integer assistantId = Integer.valueOf(userIdStr);
		order.setAssistantId(assistantId);

		if (user.getPhone() != null) {
			order.setEmployerPhone(user.getPhone());
		}

		// 推送通知
		User assistant = UserDao.getById(assistantId);
		if (assistant != null) {
			if(assistant.isIOS()){
				UMPushUtil.sendIOSCustomizedcast("新订单,用户地址:" + addressStr, null, assistant.getUserName());
			}else{
				UMPushUtil.sendAndroidCustomizedcast( "新订单", "新订单", "用户地址:" + addressStr, null, assistant.getUserName());
			}
		}

		OrderDao.saveOrder(order);
		sendMsg(order);
	}

}
